package com.opgea.crm.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.opgea.crm.common.SetupsAttributeQualifier;
import com.opgea.crm.common.SetupsModuleQualifier;
import com.opgea.crm.common.constant.ApplicationConstant;
import com.opgea.crm.common.util.DateUtil;
import com.opgea.crm.common.vo.TaskCommentVo;
import com.opgea.crm.common.vo.TaskVo;
import com.opgea.crm.domain.entities.Employee;
import com.opgea.crm.domain.entities.SetupsValue;
import com.opgea.crm.domain.entities.Task;
import com.opgea.crm.domain.entities.TaskComment;
import com.opgea.crm.domain.entities.security.CrmUser;
import com.opgea.crm.domain.modal.JsonModelMap;
import com.opgea.crm.services.EmployeeService;
import com.opgea.crm.services.ProjectDetailsService;
import com.opgea.crm.services.SetupService;
import com.opgea.crm.services.TaskService;
import com.opgea.crm.web.form.TaskForm;
import com.opgea.crm.web.modal.LoggedUser;

@Controller
@RequestMapping("projectTask")
public class ProjectTaskController {

	Logger logger = Logger.getLogger(ProjectTaskController.class);

	@Autowired
	TaskService taskService;
	@Autowired
	SetupService setupService;
	@Autowired
	EmployeeService employeeService; 
	@Autowired
	ProjectDetailsService projectDetailsService;

	@RequestMapping(method = RequestMethod.GET, value = "tasksByProjectId")
	public @ResponseBody
	Map<String, List<TaskVo>> tasksByProjectId(@RequestParam(required = false) Long projectId,
												@RequestParam(required = false) Long priorityId,
												@RequestParam(required = false) Long assigntoId,HttpServletRequest request) {
		Map<String, List<TaskVo>> tasks = null;

		if (projectId != null && projectId == 0)
			projectId = null;
		if (priorityId != null && priorityId == 0)
			priorityId = null;
		if (assigntoId != null && assigntoId == 0)
			assigntoId = null;
		
		List<TaskVo> list = this.taskService.tasksByProjectId(projectId,priorityId, assigntoId,null);
		tasks = new HashMap<String, List<TaskVo>>();
		tasks.put("data", list);

		return tasks;
	}

	@RequestMapping(method = RequestMethod.GET, value="tasksListByProjectId")
	public @ResponseBody
	Map<String,Object> tasksListByProjectId(@RequestParam(required=false, value="taskGridProjectId") Long taskGridProjectId)
	{
		logger.debug("ProjectTaskController >> showTaskList");
		if(taskGridProjectId != null){
			List<TaskVo> tasks = taskService.tasksListByProjectId(taskGridProjectId);
			return JsonModelMap.success().data(tasks);
		}else{
			return JsonModelMap.success();
		}
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "taskForme")
	public @ResponseBody
	Map<String, List<TaskVo>> taskForme(@RequestParam(required = false) Long projectId,
										@RequestParam(required = false) Long priorityId,
										@RequestParam(required = false) Long assigntoId,HttpServletRequest request) {
		Map<String, List<TaskVo>> tasks = null;

		if (projectId != null && projectId == 0)
			projectId = null;
		if (priorityId != null && priorityId == 0)
			priorityId = null;
		if (assigntoId != null && assigntoId == 0)
			assigntoId = null;
		CrmUser user=LoggedUser.getUser(request);
		List<TaskVo> list = this.taskService.tasksByProjectId(projectId,priorityId, assigntoId,user);
		tasks = new HashMap<String, List<TaskVo>>();
		tasks.put("data", list);

		return tasks;
	}

	@RequestMapping(method = RequestMethod.GET, value = "taskDropDownList")
	public @ResponseBody
	Map<String, List<SetupsValue>> taskDropDownList(@RequestParam(required = false) String operation,
													@RequestParam(required = false) Long projectId) {

		SetupsValue setupsValue = new SetupsValue(ApplicationConstant.COMBO_VALUE,ApplicationConstant.COMBO_CAPTION_ALL);
		return puplateTaskList(projectId, operation, setupsValue);
	}

	@RequestMapping(method = RequestMethod.GET, value = "deatilsDropDownList")
	public @ResponseBody
	Map<String, List<SetupsValue>> deatilsDropDownList(@RequestParam(required = false) String operation,
														@RequestParam(required = false) Long projectId) {
		return puplateTaskList(projectId, operation, null);
	}

	private Map<String, List<SetupsValue>> puplateTaskList(Long projectId,
														   String operation,
														   SetupsValue setupsValue) {
		
		Map<String, List<SetupsValue>> list = new HashMap<String, List<SetupsValue>>();
		List<SetupsValue> setupsValues = null;
		if (projectId != null && operation.equalsIgnoreCase("members")) {
			if (projectId == 0)
				projectId = null;
			setupsValues = this.taskService.allProjectAndMembers(projectId);
		}
		if (operation.equalsIgnoreCase("projects"))
			setupsValues = this.taskService.allProjects();
		if (operation.equalsIgnoreCase("priority"))
			setupsValues = this.setupService.listSetupValue(SetupsModuleQualifier.Task.ordinal(),
															SetupsAttributeQualifier.Priority.ordinal());
		if (operation.equalsIgnoreCase("status"))
			setupsValues = this.setupService.listSetupValue(SetupsModuleQualifier.Task.ordinal(),
															SetupsAttributeQualifier.Status.ordinal());

		if (operation.equalsIgnoreCase("resolution"))
			setupsValues = this.setupService.listSetupValue(SetupsModuleQualifier.Task.ordinal(),
															SetupsAttributeQualifier.Resolution.ordinal());
		if(operation.equalsIgnoreCase("units"))
			setupsValues=this.taskService.taskUnits();

		if (setupsValue != null)
			setupsValues.add(setupsValue);
			list.put("data", setupsValues);
		return list;
	}

	@RequestMapping(method = RequestMethod.POST, value = "saveTask")
	public @ResponseBody
	Long saveTask(@RequestBody TaskForm taskForm,HttpServletRequest request) {
		Task task=formToEntity(taskForm,new Task(),request);
		Long id=this.taskService.createTask(task);
		
		return id; 
	}
	
	@RequestMapping(method=RequestMethod.POST,value="updateTask")
	public @ResponseBody
	Long updateTask(@RequestBody TaskForm taskForm,HttpServletRequest request)
	{
		Task task=this.taskService.findTaskById(taskForm.getId());
		if(task!=null)
		{
			CrmUser user=LoggedUser.getUser(request);
			task.setActualEndDT(DateUtil.stringToDate(taskForm.getActualEndDT()));
			task.setActualStartDT(DateUtil.stringToDate(taskForm.getActualStartDT()));
			if(taskForm.getAssignToId()!=null)
			task.setAssignTo(this.employeeService.find(taskForm.getAssignToId()));
			task.setCreatedAt(new Date());
			task.setCreatedBy(user);
			if(taskForm.getDurationUnit()!=null)
			task.setDurationUnit(ApplicationConstant.TaskdurationUnit.valueOf(taskForm.getDurationUnit()));
			task.setEstmDuration(taskForm.getEstmDuration());
			
			task.setEstmEndDate(DateUtil.stringToDate(taskForm.getEstmEndDate()));
			task.setEstmStarDate(DateUtil.stringToDate(taskForm.getEstmStarDate()));
			if(taskForm.getMileStone()!=null){
			boolean ml=(taskForm.getMileStone().equalsIgnoreCase("on"))?true:false;
			task.setMileStone(ml);
			}
			if(taskForm.getPriorityTaskId()!=null)
			task.setPriorityId(this.setupService.findById(taskForm.getPriorityTaskId()));
			if(taskForm.getPriorityTaskId()!=null)
			task.setProjectId(this.projectDetailsService.find(taskForm.getProjectTaskId()));
			task.setTaskDetail(taskForm.getTaskDetail());
			task.setTaskName(taskForm.getTaskName());
			if(taskForm.getTaskResolutionId()!=null)
			task.setTaskResolution(this.setupService.findById(taskForm.getTaskResolutionId()));
			if(taskForm.getTaskStatusId()!=null)
				task.setTaskStatus(this.setupService.findById(taskForm.getTaskStatusId()));
			this.taskService.updateTask(task);
		}
		return taskForm.getId();
	}
	
	private Task formToEntity(TaskForm taskForm,Task task,HttpServletRequest request)
	{
		
		CrmUser user=LoggedUser.getUser(request);
		task.setActualEndDT(DateUtil.stringToDate(taskForm.getDetialActualEndDT()));
		task.setActualStartDT(DateUtil.stringToDate(taskForm.getDetialActualStartDT()));
		if(taskForm.getDetailAssignToId()!=null)
		task.setAssignTo(this.employeeService.find(taskForm.getDetailAssignToId()));
		task.setCreatedAt(new Date());
		task.setCreatedBy(user);
		if(taskForm.getDetailDurationComdo()!=null)
		task.setDurationUnit(ApplicationConstant.TaskdurationUnit.valueOf(taskForm.getDetailDurationComdo()));
		task.setEstmDuration(taskForm.getDetialEstmDuration());
		
		task.setEstmEndDate(DateUtil.stringToDate(taskForm.getDetialEstmEndDate()));
		task.setEstmStarDate(DateUtil.stringToDate(taskForm.getDetialEstmStarDate()));
		if(taskForm.getDetialMileStone()!=null){
		boolean ml=(taskForm.getDetialMileStone().equalsIgnoreCase("on"))?true:false;
		task.setMileStone(ml);
		}
		if(taskForm.getDetialPriorityId()!=null)
		task.setPriorityId(this.setupService.findById(taskForm.getDetialPriorityId()));
		if(taskForm.getDetialPriorityId()!=null)
		task.setProjectId(this.projectDetailsService.find(taskForm.getDetialProjectId()));
		task.setTaskDetail(taskForm.getDetialTaskDetail());
		task.setTaskName(taskForm.getDetialTaskName());
		if(taskForm.getDetialTaskResolutionId()!=null)
		task.setTaskResolution(this.setupService.findById(taskForm.getDetialTaskResolutionId()));
		if(taskForm.getDetialTaskStatusId()!=null)
			task.setTaskStatus(this.setupService.findById(taskForm.getDetialTaskStatusId()));
		return task;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="deleteTask")
	public @ResponseBody
	Long deleteTask(@RequestBody TaskForm taskForm)
	{
		return this.taskService.deleteTask(taskForm.getId());
	}
	
	
	@RequestMapping(method=RequestMethod.GET, value="showTaskComments")
	public @ResponseBody 
	Map<String, Object> showTaskComments(@RequestParam(required=false) Long taskId){
		List<TaskCommentVo> comments = null;
	    if(taskId!= null)
		 comments = taskService.findAllCommentsByTaskId(taskId);
		 return JsonModelMap.success().data(comments); 
	}  
	
	
	// Method to add the issue
	@RequestMapping(value="saveTaskComment", method=RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> save(@RequestBody TaskForm form,
							 @RequestParam(required=true, value="taskId")Long taskId,HttpServletRequest request) 
	{
	  
	   System.out.println("Task CommentController >> Save Task Comment >> Inside Method");
	   Task task = taskService.findTaskById(taskId);
	   
	   CrmUser crmUser=LoggedUser.getUser(request);
	   List<TaskComment> comments = task.getComments();
	   if(comments == null){
		   comments = new ArrayList<TaskComment>();
	   }
	   TaskComment taskComment = new TaskComment();
	   Employee employee = employeeService.find(form.getAssignToId());
	   SetupsValue setupValue = setupService.findById(new Long(form.getTaskStatusId()));
	   taskComment.setTask(task);
	   taskComment.setComment(form.getTaskDetail());
	   taskComment.setAssignedto(employee);
	   taskComment.setStatus(setupValue); 
	   comments.add(taskComment);
	   task.setComments(comments);
	   task.setAssignTo(employee);
	   taskComment.setCreatedAt(new Date());
	   task.setTaskStatus(setupValue);
	   taskComment.setCreatedBy(crmUser);
	   taskService.updateTask(task);
	
       return JsonModelMap.success().data(task.getId());
	  }
}
